import 'dart:async';
import 'dart:ui' as ui;
import 'package:extended_image/extended_image.dart';
import 'package:flutter/rendering.dart';

class LaraPressImgHelp {
  static final Map<String, double> _ratioCache = {};

  /// 获取图片的宽高比 (width / height)
  static Future<double?> getRatio(String img) async {
    if (img.isEmpty) return null;
    // 命中缓存
    if (_ratioCache.containsKey(img)) {
      return _ratioCache[img];
    }
    try {
      final info = await _loadImageInfo(img);
      if (info == null) return null;
      final ui.Image image = info.image;
      final ratio = image.width / image.height;
      _ratioCache[img] = ratio;
      return ratio;
    } catch (_) {
      return null;
    }
  }

  /// 根据容器宽度和图片比例计算高度
  static double calculateHeight(double containerWidth, double ratio) {
    return containerWidth / ratio;
  }

  /// 清除缓存
  static void clearCache() => _ratioCache.clear();

  /// 内部方法: 把 ImageStream 转成 Future<ImageInfo>
  static Future<ImageInfo?> _loadImageInfo(String url) {
    final provider = ExtendedNetworkImageProvider(url, cache: true);
    final stream = provider.resolve(const ImageConfiguration());

    final completer = Completer<ImageInfo?>();

    late ImageStreamListener listener;
    listener = ImageStreamListener(
      (ImageInfo info, _) {
        completer.complete(info);
        stream.removeListener(listener);
      },
      onError: (error, stackTrace) {
        completer.complete(null);
        stream.removeListener(listener);
      },
    );

    stream.addListener(listener);
    return completer.future;
  }
}
